# -*- coding=utf-8
import string
from typing import Any

from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client
from qcloud_cos.cos_exception import CosServiceError
# 1. 设置用户属性, 包括 secret_id, secret_key, region等。Appid 已在CosConfig中移除，请在参数 Bucket 中带上 Appid。Bucket 由 BucketName-Appid 组成
secret_id = 'AKIDsZ0A3f16wYtylHXXHlyvb074k9I9k47t'
secret_key = 'YooX0B5i49xVllUw73i7F6h02nIWUAaj'
region = 'ap-beijing'
appid='1307211509'
config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key)
client = CosS3Client(config)

def createBucket(name):
    '''
    创建cos 桶
    :param name:
    :return:
    '''
    bucket=f'{name}-{appid}'
    response = client.create_bucket(
        Bucket=bucket,
        ACL='public-read'# private | public-read | public-read-write,
    )
    # 设置该桶的cors 规则
    cors_config = {
        'CORSRule': [
            {
                'AllowedOrigin': '*',
                'AllowedMethod': ['GET', 'PUT', 'HEAD', 'POST', 'DELETE'],
                'AllowedHeader': "*",
                'ExposeHeader': "*",
                'MaxAgeSeconds': 500
            }
        ]
    }
    client.put_bucket_cors(
        Bucket=bucket,
        CORSConfiguration=cors_config
    )
# import uuid
#
# createBucket(str(uuid.uuid1()))

def uploadFile(name:string,file,key:string)->None:
    response = client.upload_file_from_buffer(
        Bucket=name,
        Body=file,#文件对象
        Key=key,#cos上的文件名
    )
    return f'https://{name}.cos.{region}.myqcloud.com/{key}'



def delete_file(bucket:string,key:string):
    '''
    删除cos 桶中的数据
    :param bucket: 桶
    :param key:
    :return:
    '''
    config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key)
    client = CosS3Client(config)

    client.delete_object(
        Bucket=bucket,
        Key=key
    )


def delete_file_list(bucket,key_list):
    '''
    批量删除 文件
    :param bucket:

    :param key_list:
    :return:
    '''
    config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key)
    client = CosS3Client(config)
    objects = {
        "Quiet": "true",
        "Object": key_list
    }
    client.delete_objects(
        Bucket=bucket,
        Delete=objects
    )


# delete_file('2dce9ea2-5b39-11ed-b6e4-9cb6d005a9ac-1307211509','Screenshot_20220412-102017_WeChat.jpg')
# delete_file_list('2dce9ea2-5b39-11ed-b6e4-9cb6d005a9ac-1307211509',[{'Key':'1.jpg'},{'Key':'2.jpg'},{'Key':'3.jpg'},])

def credential(bucket,):
    """ 获取cos上传临时凭证 """

    from sts.sts import Sts

    config = {
        # 临时密钥有效时长，单位是秒（30分钟=1800秒）
        'duration_seconds': 1800,
        # 固定密钥 id
        'secret_id': secret_id,
        # 固定密钥 key
        'secret_key': secret_key,
        # 换成你的 bucket
        'bucket': bucket,
        # 换成 bucket 所在地区
        'region': region,
        # 这里改成允许的路径前缀，可以根据自己网站的用户登录态判断允许上传的具体路径
        # 例子： a.jpg 或者 a/* 或者 * (使用通配符*存在重大安全风险, 请谨慎评估使用)
        'allow_prefix': '*',
        # 密钥的权限列表。简单上传和分片需要以下的权限，其他权限列表请看 https://cloud.tencent.com/document/product/436/31923
        'allow_actions': [
            # "name/cos:PutObject",
            # 'name/cos:PostObject',
            # 'name/cos:DeleteObject',
            # "name/cos:UploadPart",
            # "name/cos:UploadPartCopy",
            # "name/cos:CompleteMultipartUpload",
            # "name/cos:AbortMultipartUpload",
            "*",
        ],

    }

    sts = Sts(config)
    result_dict = sts.get_credential()
    return result_dict

# res=credential('2dce9ea2-5b39-11ed-b6e4-9cb6d005a9ac-1307211509')
# print(res)

def check_file(bucket, region, key):
    '''
    校验文件
    :param bucket:
    :param region:
    :param key:
    :return:
    '''
    config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key)
    client = CosS3Client(config)
    data = client.head_object(
        Bucket=bucket,
        Key=key
    )
    return data


def delete_bucket(bucket,region):
    '''
    删除bucket操作
    :return:
    '''
    """ 删除桶 """
    # 删除桶中所有文件
    # 删除桶中所有碎片
    # 删除桶
    config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key)
    client = CosS3Client(config)

    try:
        # 找到文件 & 删除
        while True:
            part_objects = client.list_objects(bucket)

            # 已经删除完毕，获取不到值
            contents = part_objects.get('Contents')
            if not contents:
                break

            # 批量删除
            objects = {
                "Quiet": "true",
                "Object": [{'Key': item["Key"]} for item in contents]
            }
            client.delete_objects(bucket, objects)

            if part_objects['IsTruncated'] == "false":
                break

        # 找到碎片 & 删除
        while True:
            part_uploads = client.list_multipart_uploads(bucket)
            uploads = part_uploads.get('Upload')
            if not uploads:
                break
            for item in uploads:
                client.abort_multipart_upload(bucket, item['Key'], item['UploadId'])
            if part_uploads['IsTruncated'] == "false":
                break

        client.delete_bucket(bucket)
    except CosServiceError as e:
        pass